package com.happy_lab_management.demo.admin.semester.controller;

import com.happy_lab_management.result.Result;
import com.happy_lab_management.entity.Semester;

import com.happy_lab_management.demo.admin.semester.service.SemesterService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/admin/semester")
public class SemesterController {
    @Autowired
    private SemesterService semesterService;

    /**
     * 添加新学期
     * @param semester
     * @return
     */
    @RequestMapping("/add")

    public Result<String> add(@Validated @RequestBody Semester semester){

        semesterService.save(semester);
        return Result.success("添加新学期成功");
    }

    /**
     * 列出所有学期
     * @return
     */
    @RequestMapping("/list")
    public Result<List<Semester>> list(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                       @RequestParam(name = "pageSize", defaultValue = "50") Integer pageSize
    ){
        List<Semester> semesters=semesterService.list();

        return Result.success(semesters);
    }
    // 设置平台的当前学期，设置后平台其他的所有功能都是指在“当前
    //学期”的工作。

    /**
     * 编辑学期
     * @param semester
     * @return
     */
    @RequestMapping("/edit")
    public Result<String> edit(@Validated @RequestBody Semester semester){
        // 查找数据库中对应id的学期
        Semester existingSemester = semesterService.getById(semester.getId());
        // 如果找不到对应id的学期，则返回错误信息
        if(existingSemester == null) {
            return Result.error("未找到对应id的学期");
        }
        // 更新学期名称
        existingSemester.setSemesterName(semester.getSemesterName());
        // 保存更新后的学期信息
        semesterService.updateById(existingSemester);
        return Result.success("编辑学期成功");
    }
}
